<template>
    <div class="app-container">
      <div class="filter-container">
        <el-date-picker v-model="listQuery.selectMonth" type="month" placeholder="选择月"   
        @change="jobSearch" value-format="yyyy-MM"  class="filter-item">
        </el-date-picker>
        <el-select v-model="selectedStatus" @change="SelectedStatusChange" placeholder="请选择处理状态" clearable class="filter-item" style="width: 200px;margin-left:10px;">
        <el-option v-for="(value, key) in statusList" :key="key" :label="value" :value="value" />
        </el-select>
        <el-button v-waves class="filter-item" style="margin-left:10px;"type="primary" icon="el-icon-search" @click="handleFilter">
          {{ $t('table.search') }}
        </el-button>        
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">我要投诉</el-button>
      </div>
      <!--表格内容-->
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
      >
        <el-table-column label="投诉记录ID" width="100"align="center" prop="complaintRecordId" :class-name="getSortClass('complaintRecordId')">
          <template slot-scope="{row}">
            <span>{{ row.complaintRecordId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="投诉对象" prop="complaintTarget" 
        sortable="custom" align="center" width="130" >
          <template slot-scope="{row}">
            <span>{{ row.complaintTarget }}</span>
          </template>
        </el-table-column>
        <el-table-column label="投诉原因" prop="complaintReason"
        sortable="custom" align="center" width="200" >
          <template slot-scope="{row}">
            <span>{{ row.complaintReason }}</span>
          </template>
        </el-table-column>
        <el-table-column label="联系电话" prop="telPhone" 
        sortable="custom" align="center" width="120" >
          <template slot-scope="{row}">
            <span>{{ row.telPhone }}</span>
          </template>
        </el-table-column>

        <el-table-column label="处理状态" prop="processingResult" 
        sortable="custom" align="center" width="100" >
          <template slot-scope="{row}">
            <span>{{ row.processingResult }}</span>
          </template>
        </el-table-column>

        <el-table-column label="投诉时间" prop="complaintTime" 
        sortable="custom" align="center" width="180" >
          <template slot-scope="{row}">
            <span>{{ row.complaintTime }}</span>
          </template>
        </el-table-column>

        <el-table-column label="处理人员姓名" prop="processingPersonnelName" 
        sortable="custom" align="center" width="100" >
          <template slot-scope="{row}">
            <span>{{ row.processingPersonnelName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="最新处理时间" prop="startProcessingTime" 
        sortable="custom" align="center" width="160" >
          <template slot-scope="{row}">
            <span>{{ row.startProcessingTime }}</span>
          </template>
        </el-table-column>

        <el-table-column label="处理结果" prop="note"
        sortable="custom" align="center" width="200" >
          <template slot-scope="{row}">
            <span>{{ row.note }}</span>
          </template>
        </el-table-column>
      </el-table>
       
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />     
     <!--修改的表单-->
     <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form ref="dataForm"  :rules="rules":model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">

          <el-form-item label="投诉项目" prop="complaintTarget"   >
            <el-input v-model="temp.complaintTarget" :autosize="{ minRows: 2, maxRows: 5}" type="text"placeholder="请输入投诉对象" />
          </el-form-item>
          <el-form-item label="联系电话" prop="telPhone">
            <el-input v-model="temp.telPhone" type="text" placeholder="请输入电话号码" />
          </el-form-item>
          <el-form-item label="投诉原因" prop="complaintReason">
            <el-input v-model="temp.complaintReason"  type="textarea" placeholder="请输入原因" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            {{ $t('table.cancel') }}
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            {{ $t('table.confirm') }}
          </el-button>
        </div>
      </el-dialog>

      <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
        <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
          <el-table-column prop="key" label="Channel" />
          <el-table-column prop="pv" label="Pv" />
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import dayjs from 'dayjs'; 
  import {findByPage,createComplaintRecord} from '@/api/complaintRecord'
  import waves from '@/directive/waves' // waves directive
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  export default {
    name: 'ComplexTable',
    components: { Pagination },
    directives: { waves },
    filters: {
    },
    data() {
      return {
        rules: {
          telPhone: [
            { required: true, message: "电话号码不能为空", trigger: ["blur", "change"]},
            { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: ["blur", "change"]}],
          complaintTarget: [{ required: true, message: "投诉对象不能为空", trigger: ["blur", "change"]},],
          complaintReason: [{ required: true, message: "投诉原因不能为空", trigger: ["blur", "change"]},]
      },
        temp:{
          complaintRecordId: "",
          telPhone: "",
          complaintTarget: "",
          complaintReason: "",
          processingResult: "",
          complaintTime: "",
          processingPersonnelName: "",
          startProcessingTime: "",
          note: ""
        },
        costList:{
            chargeRecordId:"",
            xianxiazhifu:"线下支付",
            cuijiao:"催缴",
            costTime:dayjs().format('YYYY-MM-DD HH:mm:ss') 
        },
        tableKey: 0,
        list: null,//表格集合数据
        total: 0,//总条数
        listLoading: true,
        listQuery: {//查询的筛选条件
          page: 1,
          limit: 10,
          selectMonth:this.getDefaultYearMonth(),
          selectedStatus:""
        },
              // 初始化用于存储选中状态值的变量
      selectedStatus: '',
        statusList:{
            status1:"待处理",
            status2:"处理中",
            status3:"已处理",
            status4:"处理失败",      
        },
        loadAllList:[],
        roomListLoad:[],
        roomListLoading: true,
        typeListLoad:[],
        typeListLoading: true,
        showReviewer: false,
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '状态更新',
          create: '投诉'
        },
         dialogPvVisible: false,
        pvData: [],
         downloadLoading: false
      }
    },
    created() {//未渲染之前  data加载之后
      this.getList();
    },
    methods: {
      SelectedStatusChange(selectedStatus) {
        this.listQuery.selectedStatus = selectedStatus;
    },
      getList() {//获取 list  total
          this.listLoading = true;
          findByPage(this.listQuery).then(response => {
            this.list = response.data.list
            this.total = response.data.total
            console.log( response.data.list)
                setTimeout(() => {
                  this.listLoading = false
                }, 1.5 * 1000)  
           })         
      }, 
     
  
      jobSearch() {
        this.getJobListByMonth();
        },
        async initData(data) {
      //获取当前时间
      var now   = new Date();
      var monthn = now.getMonth()+1;
      var yearn  = now.getFullYear();
      this.listQuery.selectMonth = yearn+"-"+monthn;
      this.selectUser = parseInt(sessionStorage.getItem("userid"));
      // this.getWeekJobList({
      //   userid: sessionStorage.getItem("userid"),
      //   weekid: "1"
      // });
        this.getJobListByMonth();
        },
    async getJobListByMonth(data) {
 
    },
    getDefaultYearMonth() {
      // 获取当前年份
      const currentYear = new Date().getFullYear();
      // 获取当前月份（注意：月份是从0开始的，所以需要加1）
      const currentMonth = new Date().getMonth() + 1;
      // 将年份和月份格式化为字符串
      const formattedYear = currentYear.toString();
      const formattedMonth = currentMonth < 10 ? '0' + currentMonth : currentMonth.toString();
      // 组合成默认展示的年月
      return `${formattedYear}-${formattedMonth}`;
    },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.status = status
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          complaintTarget:"",
          complaintReason:"",
          telPhone:""
        }
      },
      handleCreate() {        
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
      this.$refs['dataForm'].validate((valid) => {
        //判断验证是否通过
        if (valid) {   
          createComplaintRecord(this.temp).then(response => {
            //把当前内容添加到 集合中
          // this.list.unshift(this.temp)
          this.getList();
           //设置是否被不通过
           this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },

      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            //临时数据   temp内容拷贝到tempData
            const tempData = Object.assign({}, this.temp)
            //tempData
            updatComplaintRecord(tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              //替换
             // this.list.splice(index, 1, this.temp)
             this.getList();
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleFetchPv(pv) {
        
      },

      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      }
    }
  }
  </script>
  